import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhongJinTao
 * Date: 2024-02-03
 * Time: 10:23
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        //1、此处的构造方法写10，意思是有10个线程/任务
        CountDownLatch latch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            int id = i;
            Thread t = new Thread(() -> {
                Random random = new Random();
                //[0,5)
                int time = (random.nextInt(5) + 1) * 1000;
                System.out.println("线程" + id + "开始下载");
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程" + id + "结束下载");
                //2、告知CountDownLatch我执行完了
                latch.countDown();
            });
            t.start();
        }
        //3、通过这个await操作来等待所有任务结束，也就是countDown被调用10次了
        latch.await();
        System.out.println("所有任务都下载完成！");
    }
}
